import * as fs from 'fs'
import * as path from 'path'
import Config from '../config';
import ErrorType from './errors';
export async function controller(Class: string, Method: string, ctx): Promise<any> {
    let ClassObject: any = await get_controller(Class, ctx.config);
    if (ClassObject instanceof Function) {
        let d = {};
        let c = new ClassObject(ctx);
        if (c['_before_' + Method] instanceof Function) {
            await c['_before_' + Method](ctx.req.body, ctx)
        }
        if (c[Method] instanceof Function) {
            d = await c[Method](ctx.req.body, ctx)
        } else if (c['__call'] instanceof Function) {
            d = await c['__call'](ctx.req.body, ctx)
        }
        if (c['_after_' + Method] instanceof Function) {
            d = await c['_after_' + Method](d, ctx.req.body, ctx)
        }
        return d;
    } else {
        throw new Error(ErrorType.METHOD_NOT_FOUND)
    }

}
export async function get_controller(Class: string, Config: Config) {
    let cp = path.resolve(path.join(Config.AppPath, 'controller', Class));
    return require(`${cp}.js`).default;
}

// export function create_ctx():ctx {
//     return {
//         error:null,
//         path:'',
//     };
// }